//
//  HeartBeatPinger.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/9/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation
class HeartBeatPinger : NSObject{
    var socketClient:UwantSocketClient
    final let pingInterval:NSTimeInterval = 10
    final let pingTimeout:NSTimeInterval = 3
    var pingTimer:NSTimer?
    var pingTimeoutTimer:NSTimer?
    
    init(socketClient:UwantSocketClient){
        self.socketClient = socketClient
    }
    
    func start(){
        print("pinger start...")
        startPing()
        startPingTimeout(NSDate.timeIntervalSinceReferenceDate())
    }
    func startPing(){
        pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self, selector: "sendPing:", userInfo: nil, repeats: true)
    }
    func sendPing(timer:NSTimer){
        print("start ping...")
        if(ClientStatus.CONNECTED == socketClient.status){
            self.socketClient.messageSender!.sendPing()
        }
    }
    func startPingTimeout(pingSeconds:Double){
        pingTimeoutTimer?.invalidate()
        pingTimeoutTimer = nil
        let pongCost:Double = NSDate.timeIntervalSinceReferenceDate()-pingSeconds
        let delay:Double = pingInterval + pingTimeout - pongCost
        pingTimeoutTimer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: "handlePingTimeout:", userInfo: nil, repeats: false)
    }
    func handlePingTimeout(timer:NSTimer){
        print("handle ping time out")
        socketDisconnect()
    }
    func onPong(pingSeconds:Double){
        print("on pong...")
        startPingTimeout(pingSeconds)
    }
    
    func stop(){
        pingTimer?.invalidate()
        pingTimer = nil
        pingTimeoutTimer?.invalidate()
        pingTimeoutTimer = nil
    }
    
    func socketDisconnect(){
        stop()
        socketClient.disconnect(UwantSocketError.PING_TIMEOUT)
    }
}